package com.bs.visitservice.controller.seller;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.bs.visitservice.entity.SellerPhotos;
import com.bs.visitservice.service.SellerPhotosService;
import com.bs.visitservice.utils.ParamUtils;
import com.bs.visitservice.utils.Result;
import com.bs.visitservice.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * 商家照片管理
 */
@RestController
@RequestMapping("/seller")
public class SellerPhotoController {
    @Autowired
    private SellerPhotosService sellerPhotosService;

    /**
     * 查看商家照片信息
     * @param cond
     * @return
     */
    @RequestMapping(value = "/getPhotoBy",method = RequestMethod.POST)
    public Result getSellerListBy(@RequestBody Map cond){
        Map<String,Object> result = new HashMap<>();
        String sn = String.valueOf(cond.get("sellerNo"));
        if(StringUtils.isEmpty(sn)){
            result.put("total",0);
            result.put("datas",new ArrayList<>());
            return Result.success(result);
        }
        Long sellerNo = Long.valueOf(sn);
        Integer photoType = (Integer)cond.get("photoType");
        IPage page = ParamUtils.getPage(cond);
        LambdaQueryWrapper<SellerPhotos> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SellerPhotos::getSellerNo, sellerNo).eq(SellerPhotos::getPhotoType,photoType).orderByAsc(SellerPhotos::getSn);
        page = sellerPhotosService.pageMaps(page, wrapper);
        List<Map<String, Object>> res = page.getRecords();
        ResultUtil.transfort(res, getDictMap(), true);
        result.put("total",page.getTotal());
        result.put("datas",res);
        return Result.success(result);
    }

    /**
     * 照片类型 0营业执照 1店铺照片
     * @return
     */
    @RequestMapping(value = "/savePhoto",method = RequestMethod.POST)
    public Result savePhoto(HttpServletRequest request){
        InputStream is = null;
        try {
            request.setCharacterEncoding("utf-8"); //设置编码
            StandardMultipartHttpServletRequest req = (StandardMultipartHttpServletRequest) request;
            //获取formdata的值
            Iterator<String> iterator = req.getFileNames();
            Map<String, String[]> parameterMap = req.getParameterMap();
            Map<String,Object> transMap = new HashMap<>();
            parameterMap.forEach((k,v)->{
                transMap.put(k,v[0]);
            });
            SellerPhotos sellerPhotos = (SellerPhotos) ResultUtil.transObject(transMap, SellerPhotos.class);
            sellerPhotosService.lambdaUpdate().
                    eq(SellerPhotos::getSellerNo,sellerPhotos.getSellerNo()).
                    eq(SellerPhotos::getPhotoType,sellerPhotos.getPhotoType()).
                    remove();
            int i = 0;
            while (iterator.hasNext()) {
                sellerPhotos.setSn(i++);
                MultipartFile file = req.getFile(iterator.next());
                is = file.getInputStream();
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                byte[] bytes = new byte[2048];
                int len = 0;
                while ((len = is.read(bytes))>0){
                    bos.write(bytes, 0,len);
                }
                byte[] res = bos.toByteArray();
                bos.close();
                sellerPhotos.setPhoto(res);
                sellerPhotosService.save(sellerPhotos);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.success(null);
    }
    /**
     * 获取列和字典值的映射关系
     * @return
     */
    private Map getDictMap(){
        Map<String,String> dictMap = new HashMap<>();
        dictMap.put("photoType","photoType");
        return dictMap;
    }
}
